package com.sino.operation.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sino.operation.commons.ConstantValue;
import com.sino.operation.config.persistence.MyPersistence;
import com.sino.operation.entity.BizExchangeInfo;
import com.sino.operation.entity.BizOperateLog;
import com.sino.operation.entity.BizTranslist;
import com.sino.operation.entity.SysAbMessage;
import com.sino.operation.mapper.*;
import com.sino.operation.peripheral.esc.request.EscRequestParam;
import com.sino.operation.service.ExchangeService;
import com.sino.operation.util.RestTemplateUtils;
import com.sino.operation.util.StringUtil;
import com.sino.operation.vo.ExchangeVo;
import com.sino.operation.vo.PublicInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Slf4j
public class ExchangeServiceImpl implements ExchangeService {
    @Autowired
    private RestTemplateUtils restTemplateUtils;
    @Autowired
    private MyPersistence myPersistence;
    @Autowired
    private SerchMapper serchMapper;
    @Autowired
    private SysTransCenterMapper sysTransCenterMapper;
    @Override
    public Map<String, String> startExchange(EscRequestParam escRequestParam) {
        log.info("普通汇兑交易发起开始");
        //获取报文
        Object object= escRequestParam.getEscBody().getObject();
        PublicInfo publicInfo = escRequestParam.getEscBody().getPublicInfo();
        String json = JSONObject.toJSONString(object);
        ExchangeVo exchangeVo = JSONObject.parseObject(json, ExchangeVo.class);
        log.info("流程发起报文:"+exchangeVo.toString());
        SysAbMessage abMessage = new SysAbMessage();
        BizTranslist translist = new BizTranslist();
        BizExchangeInfo exchangeInfo = new BizExchangeInfo();
        BizOperateLog bizOperateLog = new BizOperateLog();
        List<Object> entityList = new ArrayList<>();
        Map<String, String> map = new HashMap<>();

        String tellPost = publicInfo.getTellerPost();
        String tellerCode = publicInfo.getTellerCode();//柜员号
        String tellerName = publicInfo.getTellerName();//柜员
        String tranDate = publicInfo.getTranDate();//发起日期
        String tranTime = publicInfo.getTranTimeStamp();//发起时间
        String orgCode = publicInfo.getOrgCode();//机构号
        String orgName = publicInfo.getOrgName();//机构名
        String imageId = publicInfo.getImageId();//影像套号
        String tranCode = publicInfo.getTranCode();//交易码
        String businessType = publicInfo.getBusinessType();//业务类型
        String account_type = exchangeVo.getACCOUNT_TYPE();//账户类型
        String postchar = exchangeVo.getPOSTCHAR();//邮电费
        String voucher_type = exchangeVo.getVOUCHER_TYPE();//凭证类型
        String journalNo = creatJournalNo(tellerCode);//生成流水号
        String centerNo = sysTransCenterMapper.selectCenter(orgCode, businessType);
        // 判断走整单还是走切片(1表示走切片，2表示走整单).从报文中取出证明文件种类，若为77、78、80、81、99，则走整单，其他情况都走切片
        String[] ts = { "", "01", "18", "23", "38", "71", "72", "73", "77", "78", "80", "81", "99" };
        List<String> types = Arrays.asList(ts);
        // 验证证明文件种类是否正确
        if (voucher_type == null || !types.contains(voucher_type)) {
            return null;
        }

        String cps_flag = null;
        // 确定切片标志 放入流程变量 加入报文 更新登记簿表
        if (!"".equals(voucher_type) && Integer.valueOf(voucher_type.trim()) < 77) {
            cps_flag = "1";
        } else {
            cps_flag = "2";
        }

        map.put("cps_flag",cps_flag);
        map.put("journalNo",journalNo);
        map.put("processInstanceId",ConstantValue.EXCHANGE);
        //流水表封装数据
        translist.setJournalNo(journalNo);
        translist.setOrgCode(orgCode);
        translist.setImageId(imageId);
        translist.setTransDate(tranDate);
        translist.setTransTime(tranTime);
        translist.setTransType(businessType);
        translist.setTransState(ConstantValue.FLOW_STATE_RUNNING);
        //封装ab表数据
        String date = new SimpleDateFormat("yyyyMMdd HH:mm:ss").format(new Date());
        String message = JSON.toJSONString(escRequestParam);
        abMessage.setJournalNo(journalNo);
        abMessage.setTime(date);
        abMessage.setMessage(message);
        abMessage.setMessageAccept(message);
        //工作簿
        exchangeInfo.setBsty(businessType);
        exchangeInfo.setJournalNo(journalNo);
        exchangeInfo.setImageId(imageId);
        exchangeInfo.setCpsFlag(cps_flag);
        exchangeInfo.setAccty(account_type);
        exchangeInfo.setPoschar(postchar);
        //日志记录
        bizOperateLog.setId(StringUtil.getId());
        bizOperateLog.setJournalNo(journalNo);
        bizOperateLog.setOperDate(date);
        bizOperateLog.setTellerPost(tellPost);
        bizOperateLog.setTellerNo(tellerName);
        entityList.add(abMessage);
        entityList.add(translist);
        entityList.add(exchangeInfo);
        entityList.add(bizOperateLog);
        myPersistence.save(entityList);

        ResponseEntity<Map> responseEntity = restTemplateUtils.post(ConstantValue.FLOWMANAGER+ConstantValue.DEPLOY_START, map,Map.class);
        Map entityBody = responseEntity.getBody();
        return  entityBody;
    }



    public String creatJournalNo(String userName){
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");//设置日期格式
        String currentTime = df.format(new Date());
        String transId = serchMapper.selectTransId();
        return "BPR"+userName+currentTime+transId.format("%05d", Integer.parseInt(transId));
    }

}
